package test.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import test.model.User;

@Controller
@SessionAttributes("user")
public class HelloWorldController {

	@RequestMapping("/login")
	public ModelAndView login() {
		return new ModelAndView("login", "command", new User());
	}
	
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public ModelAndView login(@ModelAttribute("SpringWeb") User user) {
		System.out.println("Got user " + user);
		return new ModelAndView("login", "command", new User());
	}
	
	@RequestMapping("/login/{loginId}")
	public String login(@PathVariable String loginId, HttpSession ses, @ModelAttribute("user") User user) {
		System.out.println("Logined user: " + user);
		if ( null == loginId || "".equals(loginId) ) {
			return "login";
		} else {
			User u = new User();
			u.setLoginId(loginId);
			u.setUserName("userName: " + loginId);
			ses.setAttribute("user", u);
			return "redirect:/hello";
		}
	}
	
	@RequestMapping(value="/hello")
	public ModelAndView hello(ModelAndView model, @ModelAttribute("user") User user) {
		model.addObject("msg", "Hello world! " + user.getLoginId());
		model.setViewName("helloworld");
		return model;
	}
	
	@RequestMapping(value="/step2/{vvv}")
	@ResponseBody
	public String step2() {
		return "step2 response";
	}
	
	@RequestMapping(value="/step/{vvv}")
	public String step(@PathVariable String vvv) {
		
		return "redirect:/step2/" + vvv;
	}
	
	@RequestMapping(value="/ss")
	@ResponseBody
	public String test(HttpServletRequest req, HttpSession ses) {
		
		return "Hello" + req.getRemoteAddr() + " " + new Date(ses.getCreationTime());
	}
	
}
